package com.uchedao.seller.ui.car.publish.baseinfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.TextView;

import com.nostra13.universalimageloader.utils.L;
import com.uchedao.seller.R;
import com.uchedao.seller.db.DbHelper;
import com.uchedao.seller.inf.IOnResultBack;
import com.uchedao.seller.module.Draft;
import com.uchedao.seller.config.GlobalInfo;
import com.uchedao.seller.module.Photo;
import com.uchedao.seller.ui.car.adapter.UploadPhotoAdapter;
import com.uchedao.seller.ui.car.adapter.UploadPhotoAdapter.UploadPhotoListener;
import com.uchedao.seller.util.Util;
import com.uchedao.seller.widget.NoScrollGridView;
import com.uchedao.seller.widget.dialog_for_ios.ZAlertDialog;
import com.uchedao.seller.widget.loadstate.UCheDaoRelativeLayout;

import java.io.File;

/**
 * Description: 车辆图片上传
 * Date: 2015-09-14  14:07
 * User: wushan
 */
public class UpLoadCarPicture extends UCheDaoRelativeLayout implements UploadPhotoListener,IOnResultBack {

    public static final int FROM_CAMERA_UP_LOADCARPACTURE = 101;// 拍照获取

    public static final int FROM_PICTURE_UP_LOADCARPACTURE  = 102;// 从图库获取

    private static final String[] TEXTS = {"车辆照片"};

    private   String[] NAMES ;

    private Photo[] photos;

    private TextView mNoticeMsg;

    private NoScrollGridView mPicturesGv;

    private UploadPhotoAdapter adapter;

    private int index;

    private String tmpPath;// 临时图片路径

    private AlertDialog pickerDialog;// 图片选取对话框


    public UpLoadCarPicture(Context context) {
        super(context);
    }

    public UpLoadCarPicture(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public UpLoadCarPicture(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void initView() {

        LayoutInflater.from(mContext).inflate(R.layout.view_upload_car_picture, this);
        mNoticeMsg = (TextView) findViewById(R.id.view_upload_car_picture_msg_tv);
        mPicturesGv = (NoScrollGridView) findViewById(R.id.view_upload_car_picture_gv);


    }

    @Override
    public void initDataAfterView() {

        mNoticeMsg.setText(String.format(mContext.getString(R.string.upload_car_photo_msg), 33));
        mNoticeMsg.setFocusable(true);
        mNoticeMsg.setFocusableInTouchMode(true);
        mNoticeMsg.requestFocus();
        NAMES = mContext.getResources().getStringArray(R.array.upload_photo_entries);

        photos  = clonePhotos(GlobalInfo.draft.photo);

        String[] pics = new String[NAMES.length];
        for (int i = 0; i < pics.length; i++) {
            pics[i] = photos[i] == null ? null : photos[i].pic_path;
        }
        adapter = new UploadPhotoAdapter(mContext, NAMES, pics, this);
        mPicturesGv.setAdapter(adapter);

    }

    @Override
    public void initListener() {

    }


    public Photo getPhoto(String text, String path) {
        Photo photo = new Photo();
        photo.name = text;
        photo.pic_path = path;
        return photo;
    }

    /**
     * 显示图片选取对话框
     */
    public void showPickerDialog() {
        if (pickerDialog == null) {
            CharSequence[] items = {"拍照", "从图片库选择"};
            pickerDialog = new AlertDialog.Builder(mContext).setTitle("选择")
                    .setItems(items, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                takePhoto();
                            } else {
                                Intent intent = new Intent();
                                /* 开启Pictures画面Type设定为image */
                                intent.setType("image/*");
                                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                                // intent.setAction(Intent.ACTION_GET_CONTENT);
                                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                                    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
                                } else {
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                }
								/* 取得相片后返回本画面 */
                                Context context = getContext();
                                if (context instanceof Activity) {
                                    Activity activity;
                                    activity = (Activity) context;
                                    activity.startActivityForResult(intent, FROM_PICTURE_UP_LOADCARPACTURE);
                                }
                            }
                        }
                    }).create();
        }
        pickerDialog.show();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        File file = new File(GlobalInfo.PIC_PATH, System.currentTimeMillis() + ".jpg");
        tmpPath = file.getAbsolutePath();
        Uri uri = Uri.fromFile(file);
        i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

        Context context = getContext();
        if (context instanceof Activity) {
            Activity activity = (Activity)context;
            activity.startActivityForResult(i, FROM_CAMERA_UP_LOADCARPACTURE);
        }
    }

    /**
     * 克隆Photo数组
     *
     * @param array
     * @return
     */
    private Photo[] clonePhotos(Photo[] array) {
        Photo[] photos = new Photo[array.length];
        for (int i = 0; i < array.length; i++)
            if (array[i] != null)
                photos[i] = array[i].clone();
        return photos;
    }

//    @Override
//    boolean dataChanged() {
//        for (int i = 0; i < photos.length; i++)
//            if (photos[i] == null) {
//                if (GlobalInfo.draft.photo[i] != null)
//                    return true;
//            } else if (!photos[i].equals(GlobalInfo.draft.photo[i]))
//                return true;
//        return false;
//    }

    /**
     * 得到当前完成状态
     *
     * @return
     */
    public int getStatus() {
        boolean hasEmpty = false;// 有空项
        boolean hasData = false;// 有有数据项

        for (Photo photo : photos) {
            if (photo == null || TextUtils.isEmpty(photo.pic_path)) {
                hasEmpty = true;
            } else {
                hasData = true;
            }
        }

        GlobalInfo.draft.statusChildren.put("50",hasEmpty);
//        System.out.println("ws---" + "   apapter item--status-containsKey=" + GlobalInfo.draft.statusChildren.containsKey(5 + "" + 0));
//        System.out.println("ws---" + "   apapter item--status=" + GlobalInfo.draft.statusChildren.get(5 + "" + 0));


        if (hasEmpty && hasData) {
            // 只要行驶证有，也算完成
            if (photos[0] != null && !TextUtils.isEmpty(photos[0].pic_path)) {
                return 2;// 已完成
            }
            return 1;// 进行中
        } else if (hasData)
            return 2;// 已完成
        else
            return 0;// 未开始
    }

    @Override
    public boolean save() {
        ContentValues values = new ContentValues();
        L.i("photos  " + toJson(photos));
        values.put(DbHelper.KEY_DRAFT_PHOTO, toJson(photos));
        int status = getStatus();
        values.put(DbHelper.KEY_DRAFT_PHOTO_STATUS, status);

        // 保存成功
        if (GlobalInfo.dbHelper.updateDraf(GlobalInfo.tempOwner, values)) {
            GlobalInfo.draft.photo = clonePhotos(photos);
            GlobalInfo.draft.status[Draft.TYPE_PHOTO] = status;
            return true;
        }
        return false;

    }

    @Override
    public void add(int position) {
        index = position;
        // 显示图片选择对话框
        showPickerDialog();
    }

    @Override
    public void del(final int position) {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    photos[position] = null;
                    adapter.setPic(position, "");
                }

            }
        };
        // 确认删除对话框
        new ZAlertDialog.Builder(mContext).setTitle("注意").setMessage(R.string.delete_photo_message)
                .setPositiveButton(R.string.ok, listener).setNegativeButton(R.string.cancel, listener).create().show();

    }

    public void onActivityResultView(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FROM_CAMERA_UP_LOADCARPACTURE) {
                photos[index] = getPhoto(NAMES[index], tmpPath);
                adapter.setPic(index, tmpPath);
//                autoNextTakePhoto(index);
            } else if (requestCode == FROM_PICTURE_UP_LOADCARPACTURE) {
                // dat=content://com.android.providers.media.documents/document/image:944
                Uri uri = data.getData();
                tmpPath = Util.getPath(mContext, uri);
                L.i("uri = " + uri.toString() + " path=" + tmpPath);
                photos[index] = getPhoto(NAMES[index], tmpPath);
                adapter.setPic(index, tmpPath);
            }
            //即时保存图片数据
            save();
        }
    }

    /**
     * 继续拍摄照片
     */
    public void autoNextTakePhoto(int i) {
        for(i++; i<photos.length; i++) {
            if(photos[i] == null) {
                index = i;
                takePhoto();
                return;
            }
        }
    }

//    private UploadPicUtil.OnUploadListener uploadListener = new UploadPicUtil.OnUploadListener() {
//        @Override
//        public void onProgress(String name, long transferedBytes, long totalBytes) {
//        }
//
//        @Override
//        public void onFailed(String name, String path, String result, String error) {
//            T.showShort(mContext, name+"上传失败");
//        }
//
//        @Override
//        public void onUpComplete() {
//            ProgressDialogUtil.dismissProgressDlg();
//            T.showShort(mContext, "图片上传完成");
//
//            for(Photo p : photos) {
//                if(p != null)
//                    System.out.print(p.name+": "+p.pic_url);
//            }
//        }
//    };
//
//    /**
//     * 上传图片
//     */
//    public boolean saveUpoad() {
//        UploadPicUtil upUtil = new UploadPicUtil(mContext);
//        ProgressDialogUtil.showProgressDlg(mContext, "上传图片");
//        upUtil.upload(photos, uploadListener);
//        return false;
//    }

    @Override
    public boolean dataChanged() {
        return false;
    }

}
